﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

public class XmlReaderTool:BaseObject
{
    private static XmlReaderTool self;
    public XmlReaderTool() { }

    public static XmlReaderTool getInstance()
    {
        if(self == null)
        {
            self = new XmlReaderTool();
        }
        return self;
    }

    public void LoadXml(string path,int type)
    {
        try
        {
           XmlDocument doc = new XmlDocument();
            doc.Load(path);
            HandleProperties(type.ToString(), doc);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message + "加载xml出错");
        }
    }

    /// <summary>
    /// 获取制定格式xml上的指定唯一key上的对应属性值
    /// </summary>
    /// <param name="key">指定key</param>
    /// <param name="elementName">属性</param>
    /// <returns></returns>
    public string GetXmlElementValue(int type,string key, string elementName)
    {
        return GetXmlElementValue(type,"root/fields", "field", "ID", key, elementName);
    }
    /// <summary>
    /// 获取制定格式xml上的指定节点下的唯一key上的对应属性值
    /// </summary>
    /// <param name="parentNodePath">父节点(root/fields这样的形式)</param>
    /// <param name="childNodeName">查询节点</param>
    /// <param name="matchElementName">查询唯一标识属性名</param>
    /// <param name="key">唯一key</param>
    /// <param name="elementName">要查询的属性名</param>
    /// <returns></returns>
    public string GetXmlElementValue(int type,string parentNodePath, string childNodeName, string matchElementName, string key, string elementName)
    {
        string outPut = string.Empty;
        try
        {
            XmlDocument doc = (XmlDocument)GetProperties(type.ToString());
            XmlNodeList nodes = doc.SelectSingleNode(parentNodePath).ChildNodes;
            foreach (XmlElement node in nodes)
            {
                if (node.Name == childNodeName)
                {
                    if (node.Attributes[matchElementName].Value == key)
                    {
                        outPut = node.Attributes[elementName].Value;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message + "取值出错");
        }
        return outPut;
    }

    /// <summary>
    /// 只支持DTD架构格式
    /// </summary>
    //public string GetXmlElementValueById(string id, string elementName)
    //{
    //    string outPut = string.Empty;
    //    try
    //    {
    //        XmlElement elem = doc.GetElementById(id);
    //        outPut = elem.Attributes[elementName].Value;
    //    }
    //    catch (Exception ex)
    //    {
    //        Console.WriteLine(ex.Message+"取值出错");
    //    }
    //    return outPut;
    //}




}